from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.api import taskqueue
from random_file import *
import random

class Greeting(db.Model):
    author = db.UserProperty()
    content = db.StringProperty(multiline=True)
    date = db.DateTimeProperty(auto_now_add=True)

class Generator(webapp.RequestHandler): 

    def post(self): # should run at most 1/s            

        data_num = self.request.get('num')
        zipf_int_list = []
        zipf_int_list = iniZif(data_num)           
    
        entities = []
	for i in range(int(data_num)):
            if len(entities) == 5000:
		db.put(entities)
		entities = []
            user_name = 'user' + str(zipf_int_list[i])
            author = users.User(user_name)
            content = 'I\'m ' + user_name + '....'
            rndNum = random.uniform(0, int(data_num))
            key = str(rndNum)
            greeting = Greeting(key_name=key, author=author, content=content)
	    entities.append(greeting)
	if len(entities) > 0:
            db.put(entities)

class GreetingGeneratorTask(webapp.RequestHandler):

    def post(self): # should run at most 1/s            

        data_num = self.request.get('num')
	offset = self.request.get('offset')
        zipf_int_list = []
        zipf_int_list = iniZif(data_num)

        entities = []
	i = int(offset)
	end = i + 5000
        while i < int(data_num) and i < end:
            if len(entities) == 5000:
                db.put(entities)
                entities = []
            user_name = 'user' + str(zipf_int_list[i])
            author = users.User(user_name)
            content = 'I\'m ' + user_name + '....'
	    rndNum = random.uniform(0, int(data_num))
	    key = str(rndNum)
	    greeting = Greeting(key_name=key, author=author, content=content)
            entities.append(greeting)
	    i += 1
        if len(entities) > 0:
            db.put(entities)

class GreetingGenerator(webapp.RequestHandler):
    def post(self):
        num = self.request.get('num')
        offset = self.request.get('offset')
        taskqueue.add(url='/greetingGenerateTask', params={'num': num, 'offset':offset})
        self.redirect('/')
